package com.qf.controller.admin;

import com.qf.entity.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wgy
 * @version V1.0
 * @project gp12_xiaomi
 * @package ${PACKAGE_NAME}
 * @description: ${TODO}
 * @date 2022/6/28 11:30
 */
@WebServlet(name = "AdminLoginServlet",urlPatterns = "/adminLogin")
public class AdminLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1接收数据
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if(StringUtils.isEmpty(username)){
            response.sendRedirect(request.getContextPath()+"/admin/login.jsp");
            return;
        }
        if(StringUtils.isEmpty(password)){
            response.sendRedirect(request.getContextPath()+"/admin/login.jsp");
            return;
        }
        //2创建业务对象
        UserService userService=new UserServiceImpl();
        try {
            User user=userService.login(username,password);
            //3是否是管理管理员
            if(user!=null&&user.getRole()==0){//管理员
                request.getSession().setAttribute("admin", user);
                response.sendRedirect(request.getContextPath()+"/admin/admin.jsp");
            }else{
                response.sendRedirect(request.getContextPath()+"/admin/login.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect(request.getContextPath()+"/admin/login.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
